package com.grant.code.service.impl;

import com.grant.code.service.VideoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 视频服务实现类 - 处理用户视频的存储和访问
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Value("${app.storage.videos:./data/videos}")
    private String baseVideoDirectory;
    
    private static final String[] SUPPORTED_VIDEO_EXTENSIONS = {".mp4", ".avi", ".mkv", ".mov", ".wmv"};
    
    @Override
    public List<File> getUserVideos(Integer userId) {
        File userDir = getUserVideoDirectory(userId);
        if (!userDir.exists() || !userDir.isDirectory()) {
            return new ArrayList<>();
        }
        
        File[] files = userDir.listFiles(file -> {
            if (!file.isFile()) {
                return false;
            }
            String name = file.getName().toLowerCase();
            return Arrays.stream(SUPPORTED_VIDEO_EXTENSIONS)
                    .anyMatch(ext -> name.endsWith(ext));
        });
        
        return files != null ? Arrays.asList(files) : new ArrayList<>();
    }

    @Override
    public File saveUserVideo(Integer userId, File videoFile) throws IOException {
        if (videoFile == null || !videoFile.exists() || !isVideoFile(videoFile)) {
            throw new IllegalArgumentException("无效的视频文件");
        }
        
        // 确保用户视频目录存在
        File userDir = getUserVideoDirectory(userId);
        if (!userDir.exists() && !userDir.mkdirs()) {
            throw new IOException("无法创建用户视频目录: " + userDir.getAbsolutePath());
        }
        
        // 生成唯一文件名以避免冲突
        String originalName = videoFile.getName();
        String extension = originalName.substring(originalName.lastIndexOf('.'));
        String newFileName = UUID.randomUUID().toString() + extension;
        
        File destFile = new File(userDir, newFileName);
        Files.copy(videoFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        
        return destFile;
    }

    @Override
    public boolean deleteUserVideo(Integer userId, String videoFileName) {
        if (StringUtils.isEmpty(videoFileName)) {
            return false;
        }
        
        File userDir = getUserVideoDirectory(userId);
        File videoFile = new File(userDir, videoFileName);
        
        // 确保文件存在并且在用户目录中
        if (!videoFile.exists() || !videoFile.getParentFile().equals(userDir)) {
            return false;
        }
        
        // 尝试删除视频文件
        return videoFile.delete();
    }
    
    @Override
    public File renameUserVideo(Integer userId, String oldFileName, String newFileName) throws IOException {
        // 参数验证
        if (StringUtils.isEmpty(oldFileName) || StringUtils.isEmpty(newFileName)) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        // 确保新文件名包含扩展名
        String extension = "";
        int dotIndex = oldFileName.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = oldFileName.substring(dotIndex);
        }
        
        if (!newFileName.endsWith(extension)) {
            newFileName += extension;
        }
        
        // 不允许使用不合法的文件名字符
        if (newFileName.contains("/") || newFileName.contains("\\") || 
            newFileName.contains(":") || newFileName.contains("*") || 
            newFileName.contains("?") || newFileName.contains("\"") || 
            newFileName.contains("<") || newFileName.contains(">") || 
            newFileName.contains("|")) {
            throw new IllegalArgumentException("文件名包含不允许的字符");
        }
        
        // 获取文件路径
        File userDir = getUserVideoDirectory(userId);
        File oldFile = new File(userDir, oldFileName);
        File newFile = new File(userDir, newFileName);
        
        // 验证旧文件存在且在用户目录中
        if (!oldFile.exists() || !oldFile.getParentFile().equals(userDir)) {
            throw new IOException("找不到原始文件");
        }
        
        // 检查新文件名是否已存在
        if (newFile.exists()) {
            throw new IOException("文件名已存在");
        }
        
        // 执行重命名
        if (!oldFile.renameTo(newFile)) {
            throw new IOException("重命名失败");
        }
        
        return newFile;
    }

    @Override
    public File getUserVideoDirectory(Integer userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        Path userDirPath = Paths.get(baseVideoDirectory, "user_" + userId);
        return userDirPath.toFile();
    }

    @Override
    public boolean initUserVideoDirectory(Integer userId) {
        File userDir = getUserVideoDirectory(userId);
        if (userDir.exists()) {
            return userDir.isDirectory();
        }
        return userDir.mkdirs();
    }
    
    /**
     * 检查文件是否为视频文件
     * 
     * @param file 要检查的文件
     * @return 是否为视频文件
     */
    private boolean isVideoFile(File file) {
        if (file == null || !file.exists() || !file.isFile()) {
            return false;
        }
        
        String fileName = file.getName().toLowerCase();
        return Arrays.stream(SUPPORTED_VIDEO_EXTENSIONS)
                .anyMatch(fileName::endsWith);
    }
} 